package com.cqupt.tr.component.role;


import com.cqupt.tr.Utils.AccessAddressUtil;
import com.cqupt.tr.Utils.DateUtil;
import com.cqupt.tr.Utils.ObjectJsonTransFunction;
import com.cqupt.tr.Utils.RedisUtils;
import com.cqupt.tr.bean.BaseMessage;
import com.cqupt.tr.bean.JwtUser;
import com.cqupt.tr.bean.LoginUser;
import com.cqupt.tr.component.JwtTokenUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by root on 2019/2/27.
 */
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Value("${token.expirationSeconds}")
    private int expirationSeconds;
    @Value("${token.validTime}")
    private int validTime;
    @Autowired
    private RedisUtils redisUtil;

    private static final Logger log = LoggerFactory.getLogger(AjaxAuthenticationSuccessHandler.class);


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        //方式一
        /*JwtUser userDetails = (JwtUser) authentication.getPrincipal();
        String role = "";
        // 因为在JwtUser中存了权限信息，可以直接获取，由于只有一个角色就这么干了
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            role = authority.getAuthority();
        }
        String jwtToken = JwtTokenUtils.createToken(userDetails.getUsername(), role,false);
        //将生成的token放入header
        httpServletResponse.setHeader("Authorization", JwtTokenUtils.TOKEN_PREFIX + jwtToken);
        httpServletResponse.getWriter().write(JSON.toJSONString(ResultVO.result(ResultEnum.USER_LOGIN_SUCCESS,jwtToken,true)));*/

        //方式二
        //1、根据ip、role、name生成token

        try{
  //          LoginUser loginUser = new ObjectMapper().readValue(httpServletRequest.getInputStream(), LoginUser.class);
            JwtUser userDetails = (JwtUser) authentication.getPrincipal();
            String role = "";
            // 因为在JwtUser中存了权限信息，可以直接获取，由于只有一个角色就这么干了
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                role = authority.getAuthority();
            }
            String ip = AccessAddressUtil.getIpAddress(httpServletRequest);
            Map<String,Object> map = new HashMap<>();
            map.put("ip",ip);
            map.put("role",role);
            //token的有效期为5分钟
            String jwtToken = JwtTokenUtils.createToken(userDetails.getUsername(),map,false);
            //2、设置token刷新的截止时间为
//        Integer expire = validTime*24*60*60*1000;
            Integer expire = 60*60;  //半小时
            //获取请求的ip地址
            Jedis jedis = redisUtil.getJedis();
            jedis.hset(jwtToken,"tokenValidTime", DateUtil.getAddDaySecond(60*30));
            jedis.hset(jwtToken,"expirationTime",DateUtil.getAddDaySecond(300));
            jedis.hset(jwtToken,"username",userDetails.getUsername());
            jedis.hset(jwtToken,"role",role);
            jedis.hset(jwtToken,"ip",ip);
            jedis.hset(jwtToken,"userauth",ObjectJsonTransFunction.toJsonStr(userDetails.getMonitorAuth()));
            jedis.expire(jwtToken,expire);
         //   jedis.set(jwtToken,userDetails.getUsername()+":"+currentIp,"nx","ex",expire);
        //    jedis.set(jwtToken,userDetails.getUsername(),currentIp,role,expire);
            jedis.close();
            log.info("用户{}登录成功，信息已保存至redis",userDetails.getUsername());

            BaseMessage message =new BaseMessage();
            message.setCode("0");
            message.setMsg("success");
            message.setData(jwtToken);
            //将生成的token放入header
            httpServletResponse.setHeader("Authorization", JwtTokenUtils.TOKEN_PREFIX + jwtToken);
            httpServletResponse.getWriter().write(ObjectJsonTransFunction.toJsonStr(message));
        }catch (Exception e){
            e.printStackTrace();
        }


    }


}
